<template>
  <div class="music-detail-container fade-in">
    <!-- 主要内容区域 -->
    <div class="music-detail-card content-stagger">
      <!-- 左侧封面和播放区域 -->
      <div class="cover-section scale-in">
        <div class="cover-wrapper">
          <img
            :src="
              music.coverUrl || 'https://via.placeholder.com/400x400/3498db/ffffff?text=音乐封面'
            "
            :alt="music.title"
            class="cover-image"
            @error="handleImageError"
          />
        </div>

        <!-- 封面下方信息区域 -->
        <div class="cover-info">
          <div class="basic-info">
            <p class="duration">时长: {{ formatTime(music.duration || 0) }}</p>
            <p class="upload-time">上传于 {{ formatDate(music.createTime) }}</p>
          </div>
        </div>
      </div>

      <!-- 右侧信息区域 -->
      <div class="info-section">
        <!-- 标题和艺术家 -->
        <div class="header-info">
          <h1 class="music-title">{{ music.title || '未知标题' }}</h1>
        </div>

        <!-- 上传者信息 -->
        <div class="uploader-section">
          <h3 class="section-title">上传者</h3>
          <div class="uploaders-list">
            <div
              v-for="(uploader, index) in uploaders"
              :key="uploader.id"
              class="uploader-mini-card"
              @click="goToUserProfile(uploader.id)"
              :style="{ animationDelay: `${index * 0.1}s` }"
            >
              <img
                v-if="uploader.avatar"
                :src="uploader.avatar"
                :alt="uploader.nickname || uploader.username"
                class="uploader-mini-avatar"
              />
              <div v-else class="uploader-mini-avatar avatar-placeholder">
                {{ (uploader.nickname || uploader.username).charAt(0) }}
              </div>
              <div class="uploader-mini-name">{{ uploader.nickname || uploader.username }}</div>
            </div>
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="basic-info-cards">
          <div class="info-item">
            <span class="info-label">专辑</span>
            <a
              v-if="music.albumId"
              href="#"
              class="info-value link"
              @click.prevent="goToAlbum(music.albumId)"
            >
              {{ music.albumTitle || '未命名专辑' }}
            </a>
            <span v-else class="info-value">未收录专辑</span>
          </div>

          <div class="info-item">
            <span class="info-label">曲风</span>
            <span class="info-value">{{ music.genreName || '未知曲风' }}</span>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button class="btn btn-primary" @click="playMusic">立即播放</button>
          <button class="btn btn-tertiary" @click="shareMusic">分享</button>
        </div>

        <!-- 音乐描述 -->
        <div class="music-description" v-if="music.description">
          <h3 class="description-title">音乐描述</h3>
          <div class="description-text">
            <p>{{ music.description }}</p>
          </div>
        </div>
        <div class="music-description" v-else>
          <h3 class="description-title">音乐描述</h3>
          <div class="description-text">
            <p>暂无描述</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getMusicById } from '../api/music'
import { getUserInfoById } from '../api/user'
import { useEventBus } from '../utils/eventBus'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const music = ref({})
const eventBus = useEventBus()
const musicId = route.params.id

// 上传者列表
const uploaders = ref([])

// 获取音乐详情
const fetchMusicDetail = async () => {
  try {
    const response = await getMusicById(musicId)
    if (response && response.code === 200) {
      music.value = response.data
      console.log('音乐详情数据:', response.data)

      // 处理创作者昵称，与首页保持一致
      const creatorIds = music.value.creatorIds || music.value.creator_ids || ''
      if (creatorIds && creatorIds.trim() !== '') {
        const ids = creatorIds
          .split('-')
          .map((id) => parseInt(id.trim()))
          .filter((id) => !isNaN(id))

        if (ids.length > 0) {
          try {
            const userPromises = ids.map((id) => getUserInfoById(id))
            const userResponses = await Promise.allSettled(userPromises)

            const nicknames = userResponses.map((result, index) => {
              if (result.status === 'fulfilled') {
                const userData = result.value.data
                return userData.nickname || userData.username || `用户${ids[index]}`
              } else {
                return `用户${ids[index]}`
              }
            })

            // 设置创作者昵称字段，与首页保持一致
            music.value.creatorNicknames = nicknames
            music.value.creatorNickname = nicknames[0] || '未知用户'
          } catch (error) {
            console.error('获取创作者昵称失败:', error)
            music.value.creatorNickname = '未知用户'
            music.value.creatorNicknames = ['未知用户']
          }
        } else {
          music.value.creatorNickname = '未知用户'
          music.value.creatorNicknames = ['未知用户']
        }
      } else {
        music.value.creatorNickname = '未知用户'
        music.value.creatorNicknames = ['未知用户']
      }
    } else {
      console.error('获取音乐详情失败:', response?.msg)
    }
  } catch (error) {
    console.error('Failed to fetch music detail:', error)
  }
  // 获取上传者详细信息
  await fetchUploadersDetail()
}

// 获取上传者详细信息
const fetchUploadersDetail = async () => {
  try {
    let creatorIds = music.value.creatorIds || music.value.creator_ids || ''

    console.log('获取上传者详情:', { creatorIds })

    if (!creatorIds || creatorIds.trim() === '') {
      console.log('没有上传者ID数据')
      return
    }

    // 分割ID并获取真实用户信息
    const ids = creatorIds
      .split('-')
      .map((id) => parseInt(id.trim()))
      .filter((id) => !isNaN(id))

    // 并发获取所有用户信息
    const userPromises = ids.map((id) => getUserInfoById(id))
    const userResponses = await Promise.allSettled(userPromises)

    uploaders.value = userResponses.map((result, index) => {
      if (result.status === 'fulfilled') {
        const userData = result.value.data
        return {
          id: ids[index],
          username: userData.username || `用户${ids[index]}`,
          nickname: userData.nickname || userData.username || `用户${ids[index]}`,
          avatar:
            userData.avatarUrl ||
            `https://via.placeholder.com/60x60/27ae60/ffffff?text=${(userData.nickname || userData.username || ids[index].toString()).charAt(0).toUpperCase()}`,
        }
      } else {
        // 如果获取失败，使用占位符
        return {
          id: ids[index],
          username: `用户${ids[index]}`,
          nickname: null,
          avatar: `https://via.placeholder.com/60x60/27ae60/ffffff?text=${ids[index].toString().charAt(0)}`,
        }
      }
    })

    console.log('上传者详情已设置:', uploaders.value)
  } catch (error) {
    console.error('获取上传者详情失败:', error)

    // 错误时回退到简单ID列表
    const creatorIds = music.value.creatorIds || music.value.creator_ids || ''
    const ids = creatorIds
      .split('-')
      .map((id) => parseInt(id.trim()))
      .filter((id) => !isNaN(id))
    uploaders.value = ids.map((id) => ({
      id,
      username: `用户${id}`,
      nickname: null,
      avatar: `https://via.placeholder.com/60x60/27ae60/ffffff?text=${id.toString().charAt(0)}`,
    }))
  }
}

// 播放控制
const playMusic = () => {
  eventBus.emit('playMusic', music.value)
}



// 分享音乐
const shareMusic = () => {
  // 实现分享功能
  const shareUrl = `${window.location.origin}/music/${musicId}`
  if (navigator.share) {
    navigator.share({
      title: music.value.title,
      text: `听听这首音乐: ${music.value.title}`,
      url: shareUrl,
    })
  } else {
    // 复制到剪贴板
    navigator.clipboard.writeText(shareUrl)
    // 这里可以添加提示
    ElMessage.success('链接已复制到剪贴板')
  }
}

// 简化日期格式化
const formatDate = (dateString) => {
  if (!dateString) return '未知时间'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  })
}

// 格式化时间
const formatTime = (seconds) => {
  if (!seconds || isNaN(seconds)) return '00:00'
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 图片错误处理
const handleImageError = (event) => {
  event.target.src = 'https://sky-take-ou7.oss-cn-beijing.aliyuncs.com/default.jpeg'
}

// 跳转到专辑页面
const goToAlbum = (albumId) => {
  if (albumId) {
    router.push(`/album/${albumId}`)
  }
}

// 跳转到用户主页
const goToUserProfile = (userId) => {
  if (userId) {
    router.push(`/profile/${userId}`)
  }
}

onMounted(() => {
  fetchMusicDetail()
})
</script>

<style scoped>
.music-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1rem;
  /* background: linear-gradient(135deg, #f8fff8 0%, #f0f9f0 100%); */
  min-height: 100vh;
}

.music-detail-card {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 3rem;
  background: white;
  border-radius: 16px;
  padding: 2.5rem;
  box-shadow: 0 8px 32px rgba(39, 174, 96, 0.1);
  margin-bottom: 2rem;
}

/* 封面区域 */
.cover-section {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.cover-wrapper {
  position: relative;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  background-color: #f0f0f0;
}

.cover-image {
  width: 100%;
  height: 100%;
  aspect-ratio: 1 / 1;
  object-fit: cover;
  object-position: center;
  transition: transform 0.3s ease;
}

.cover-wrapper:hover .cover-image {
  transform: scale(1.1);
}

.cover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(39, 174, 96, 0.8), rgba(46, 204, 113, 0.8));
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.cover-wrapper:hover .cover-overlay {
  opacity: 1;
}

.play-btn {
  width: 80px;
  height: 80px;
  background: white;
  border: none;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.play-btn:hover {
  transform: scale(1.1);
}

.play-btn i {
  font-size: 2rem;
  color: #27ae60;
  margin-left: 4px;
}

/* 信息区域 */
.info-section {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.header-info {
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 1.5rem;
}

.music-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 0.5rem;
  line-height: 1.2;
}

.info-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.info-card {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1.25rem;
  background: #f8f9fa;
  border-radius: 12px;
  border-left: 4px solid #27ae60;
  transition: transform 0.3s ease;
}

.info-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.info-icon {
  width: 40px;
  height: 40px;
  background: #27ae60;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 1.2rem;
}

.info-content {
  display: flex;
  flex-direction: column;
}

.info-label {
  font-size: 0.875rem;
  color: #666;
  margin-bottom: 0.25rem;
}

.info-value {
  font-size: 1rem;
  font-weight: 600;
  color: #2c3e50;
}

.info-value.link {
  color: #27ae60;
  cursor: pointer;
  text-decoration: none;
}

.info-value.link:hover {
  text-decoration: underline;
}

.info-value.status {
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  font-size: 0.875rem;
  font-weight: 500;
}

.info-value.status.approved {
  background: #d4edda;
  color: #155724;
}

.info-value.status.pending {
  background: #fff3cd;
  color: #856404;
}

.info-value.status.rejected {
  background: #f8d7da;
  color: #721c24;
}

/* 描述区域 */
.description-section {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 1.5rem;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1.25rem;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 1rem;
}

.description-content p {
  color: #666;
  line-height: 1.8;
  margin: 0;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 50px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
}

.btn-primary {
  background: #27ae60;
  color: white;
}

.btn-primary:hover {
  background: #219a52;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(39, 174, 96, 0.3);
}



.btn-tertiary {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #e0e0e0;
}

.btn-tertiary:hover {
  background: #e9ecef;
}

/* 上传者样式 */
.uploader-section {
  margin-bottom: 2rem;
}

.uploaders-list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.75rem;
}

.uploader-mini-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.25rem;
  padding: 0.75rem;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 80px;
}

.uploader-mini-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  background: #e8f5e8;
}

.uploader-mini-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #27ae60;
}

.uploader-mini-name {
  font-size: 0.75rem;
  font-weight: 500;
  color: #2c3e50;
  text-align: center;
  line-height: 1.2;
  max-width: 70px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 封面下方信息 */
.cover-info {
  margin-top: 1rem;
  text-align: center;
}

.basic-info p {
  margin: 0.5rem 0;
  color: #666;
  font-size: 0.9rem;
}

/* 音乐描述 */
.music-description {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 1.5rem;
  margin-top: 2rem;
}

.description-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 1rem;
}

.description-text p {
  color: #666;
  line-height: 1.8;
  margin: 0;
}

/* 基本信息卡片 */
.basic-info-cards {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-weight: 600;
  color: #2c3e50;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .music-detail-card {
    grid-template-columns: 1fr;
    gap: 2rem;
    padding: 1.5rem;
  }

  .cover-image {
    aspect-ratio: 1 / 1;
  }

  .info-cards {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-direction: column;
  }

  .related-music-grid {
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
  }

  .uploaders-list {
    justify-content: center;
  }

  .uploader-mini-card {
    min-width: 70px;
    padding: 0.5rem;
  }

  .uploader-mini-avatar {
    width: 35px;
    height: 35px;
  }

  .uploader-mini-name {
    font-size: 0.7rem;
    max-width: 60px;
  }
}

@media (max-width: 480px) {
  .related-music-grid {
    grid-template-columns: 1fr;
  }

  .uploaders-list {
    gap: 0.5rem;
  }

  .uploader-mini-card {
    min-width: 65px;
    padding: 0.4rem;
  }
}
</style>
